import _ from 'lodash'
import CategoryModel from '../Category'
import * as ProductApi from '@/api/product'
import * as BrandApi from '@/api/brand'

/**
 * 商品 model类
 * ProductModel
 */
export default {

    // 当前商品ID
    spu: null,

    // 表单数据
    formData: {
        // 当前商品记录
        product: {},
        // 分类列表
        categoryList: [],
        // 品牌列表
        brandList: []
    },

    // 获取form所需的数据
    getFromData(spu = null) {
        // 记录商品ID (编辑时)
        this.spu = spu
        return new Promise((resolve, reject) => {
            Promise.all([
                // 获取商品详情信息(编辑时)
                this.getGoodsDetail(spu),
                // 获取分类列表
                this.getCategoryList(),
                // 获取品牌列表
                this.getBrandList(),
            ]).then(() => {
                // 设置默认数据
                resolve({formData: this.formData})
            })
        })
    },

    // 获取商品详情
    getGoodsDetail(spu = null) {
        if (!spu) return false
        return new Promise((resolve, reject) => {
            ProductApi.detail(spu)
                .then(result => {
                    this.formData.product = result
                    resolve()
                })
        })
    },

    // 获取表单默认值(用于form.setFieldsValue的数据)
    getFieldsValue() {
        // 商品详情信息
        const product = this.formData.product
        // 格式化categoryIds
        product.catNo = [product.catRootNo, product.catParentNo, product.catNo]
        // 商品基本数据
        const productFormData = _.pick(product, [
            'catNo', 'brandNo', 'productName', 'remark',
            'deductStockType', 'restrict', 'restrictTotal', 'restrictSingle',
            'desc'
        ])
        return {
            ...productFormData,
        }
    },

    // 第二次赋值 (适用于动态渲染的form-item)
    getFieldsValue2() {
        const product = this.formData.product
        let goodsFormData = {}
        // 商品限购数据
        if (product.restrict && product.restrict === 1) {
            goodsFormData['restrictTotal'] = product['restrictTotal']
            goodsFormData['restrictSingle'] = product['restrictSingle']
        }
        return goodsFormData
    },

    // 获取分类列表
    getCategoryList() {
        return new Promise((resolve, reject) => {
            CategoryModel.getCategoryTreeSelect()
                .then(list => {
                    this.formData.categoryList = list
                    resolve()
                })
        })
    },

    // 获取品牌列表
    getBrandList() {
        return new Promise((resolve, reject) => {
            BrandApi.options()
                .then(list => {
                    this.formData.brandList = list
                    resolve()
                })
        })
    },
}
